<template>
	<div id='page__goods-edit'>
		<header class="page__header">
			<h2 class="page__title">{{title}}</h2>
			<el-button
				v-if="isEdit"
				type="primary"
				size="mini"
				@click="$router.replace('/goods/edit')"
			>
				新增商品
			</el-button>
		</header>
		<div class="page__main" v-loading="loading">
			<el-form
				ref="form"
				:model="form"
				:rules="rules"
				label-width="80px">
				<el-form-item label="商品名称" prop="name">
					<el-input
						v-model="form.name"
						size="small"
						@input="changeName"
						@blur="validateName"
						placeholder="请输入商品名称">
						<i
							v-if="nameLoading"
							slot="suffix" class="el-icon-loading"></i>
					</el-input>
				</el-form-item>
				<el-form-item label="商品类别" prop="categoryId">
					<el-select
						v-model="form.categoryId"
						filterable
						allow-create
						size="small"
						placeholder="请选择商品类别">
						<el-option
							v-for="item in categories"
							:key="item.id"
							:label="item.name"
							:value="item.id">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px;margin-left: 8px">
								<el-tag
									v-if="!item.parentId"
									size="mini"
									type="success">主类别</el-tag>
								<el-tag
									v-else
									size="mini"
									type="warning">二级类别</el-tag>
							</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品品牌" prop="brandId">
					<el-select
						v-model="form.brandId"
						filterable
						size="small"
						placeholder="请选择商品品牌">
						<el-option
							v-for="item in brandList"
							:key="item.id"
							:label="item.name"
							:value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品参数" prop="paramsValue">
					<div class="params">
						<el-input
							style="width: 174px"
							v-model="form.paramsValue"
							size="small"
							type="number"
							:min="0"
							placeholder="参数值"></el-input>
						<el-select
							v-model="form.paramsId"
							filterable
							size="small"
							placeholder="参数单位">
							<el-option
								v-for="item in paramsList"
								:key="item.id"
								:label="item.name"
								:value="item.id">
							</el-option>
						</el-select>
					</div>
				</el-form-item>
				<el-form-item label="价格" prop="price">
					<el-input
						v-model="form.price"
						size="small"
						type="number"
						:min="0"
						placeholder="请输入商品价格"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-select
						v-model="form.status"
						filterable
						allow-create
						size="small"
						placeholder="请选择状态">
						<el-option
							v-for="item in GOODS_STATUS_LIST"
							:key="item.value"
							:label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="图片" class="img-content">
					<div class="img-bar">
						<div
							v-for="(item, index) in form.imgList"
							:key="index"
							class="image-item">
							<el-image :src="item.img">
								<div slot="error" class="image-slot">
									无图片
								</div>
							</el-image>
							<div
								v-if="!!item"
								class="image-operate">
								<i
									class="el-icon-delete"
									@click="deleteImgItem(index)"
								></i>
							</div>
						</div>

						<el-button
							type="warning"
							size="mini"
							@click="editImg"
						>
							新增图片
						</el-button>
					</div>
				</el-form-item>
				<el-form-item label="">
					<div class="operate-bar">
						<el-button
							type="primary"
							size="small"
							@click="saveGoods"
						>
							确定
						</el-button>
						<el-button
							size="small"
							@click="$router.push('/goods/manage')"
						>
							取消
						</el-button>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<img-edit title="编辑商品图片" @submit="updateBase64"/>
	</div>
</template>

<script>
  /**
   *
   *
   *
   */
  import {mapState} from 'vuex'
  import * as CONSTANT from '../../config/constant'
  import imgEdit from './img-edit'

  const defaultForm = {
    id: '',
    name: '',
    categoryId: '',
    brandId: '',
    paramsValue: '',
    paramsId: '',
    price: '',
    status: CONSTANT.GOODS_VALID,
    imgList: []
  }
  export default {
    name: "edit",
    data() {
      return {
        ...CONSTANT,
        goods: {},
        form: {
          ...defaultForm,
          imgList: []
        },
        nameError: undefined,
        rules: {
          name: [{required: true, message: '请输入商品名称'}, {
            validator: (rule, value, callback) => {
              callback(this.nameError)
            }
          }],
          categoryId: [{required: true, message: '请选择商品类别'}],
          brandId: [{required: true, message: '请选择商品品牌'}],
          paramsValue: [{required: true, message: '请输入参数值'}, {
            trigger: 'change',
            validator: (rule, value, callback) => {
              let {paramsValue, paramsId} = this.form
              if (!paramsValue) {
                callback('请输入参数值')
              } else if (!paramsId) {
                callback('请选择参数单位')
              } else {
                callback()
              }
            }
          }],
          price: [{required: true, message: '请输入价格'}, {
            validator: (rule, value, callback) => {
              if (value < 0) {
                callback("价格不能小于0");
              } else {
                callback()
              }
            }
          }],
        },
        loading: false,
        nameLoading: false,
      }
    },
    computed: {
      ...mapState([
        'categories',
        'brandList',
        'paramsList'
      ]),
      isEdit() {
        let {id} = this.$route.query
        return id > 0
      },
      title() {
        let isEdit = this.isEdit,
          goods = this.goods
        if (!isEdit) return '新增商品'
        if (goods.name) return '编辑 ' + goods.name
        return '编辑商品'
      },
      params() {
        let categories = this.categories
        let params = {
          ...this.form
        }
        if (categories.findIndex(item => item.id === params.categoryId) === -1) {
          params.categoryName = params.categoryId
          delete params.categoryId
        }
        params.imgList = params.imgList.map((item, index) => {
          if (index !== 0 && item.id) {
            delete item.img
          }
          return {
            ...item
          }
        })
        params.imgList = JSON.stringify(params.imgList)
        return params
      }
    },
    watch: {
      $route: {
        deep: true,
        immediate: true,
        handler() {
          this.goods = {}
          this.$nextTick(() => {
            this.$refs.form && this.$refs.form.clearValidate()
          })
          this.getGoods()
        }
      },
      nameError() {
        this.$refs.form && this.$refs.form.validateField('name')
      }
    },
    mounted() {
      this.$store.dispatch('getCategories')
      this.$store.dispatch('getBrandList')
      this.$store.dispatch('getParamsList')
    },
    methods: {
      changeName() {
        this.nameError = undefined
      },
      validateName() {
        this.nameLoading = true
        let nameError = undefined
        this.$axios.post('/goods/isNameValid', this.params, {
            abort: true
          })
          .then(({success, message, data}) => {
            if (!success) {
              nameError = message
            }
          })
          .catch(({message}) => {
            this.$message({
              type: 'error',
              message: message
            })
          })
          .finally(() => {
            this.nameLoading = false
            this.nameError = nameError
          })
      },
      setForm() {
        let goods = this.goods || {}
        let form = {}
        Object.keys(defaultForm).forEach(key => {
          if (goods[key] !== null && goods[key] !== undefined) {
            form[key] = goods[key]
          } else {
            form[key] = defaultForm[key]
          }
        })
        this.form = form
      },
      updateBase64(data) {
        this.form.imgList.push({
          img: data
        })
      },
      deleteImgItem(index) {
        this.form.imgList.splice(index, 1)
      },
      getGoods() {
        let {id} = this.$route.query
        this.setForm()
        if (!id) {
          this.loading = false
          return
        }
        this.loading = true
        this.$axios.get('/goods/info', {
            params: {
              id: id
            },
            abort: true
          })
          .then(({success, message, data}) => {
            if (success) {
              this.goods = data
              this.setForm()
            } else {
              this.$message({
                type: 'error',
                message: message
              })
            }
          })
          .catch(({message}) => {
            this.$message({
              type: 'error',
              message: message
            })
          })
          .finally(() => {
            this.loading = false
          })
      },
      editImg() {
        this.$bus.$emit('goods-img__edit')
      },
      saveGoods() {
        this.$refs.form.validate(valid => {
          if (!valid) return false
          this.loading = true
          let categories = this.categories
          this.$axios.post('/goods/save', this.params)
            .then(({success, message, data}) => {
              if (success) {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.$router.push('/goods/manage')
              } else {
                if (/商品名称/.test(message)) {
                  this.nameError = message
                } else {
                  this.$message({
                    type: 'error',
                    message: message
                  })
                }
              }
            })
            .catch(({message}) => {
              this.$message({
                type: 'error',
                message: message
              })
            })
            .finally(() => {
              this.loading = false
            })
        })
      }
    },
    components: {
      imgEdit
    }
  }
</script>

<style lang='less'>
	#page__goods-edit {

		.el-form {
			max-width: 100% !important;

			.el-form-item__content {
				max-width: 500px;
			}

			.img-content {
				.el-form-item__content {
					max-width: 100%;
				}
			}
		}

		.el-image {
			width: 280px;
			height: 168px;

			.image-slot {
				width: 100%;
				height: 100%;
				background-color: #f5f7fa;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #c0c4cc;
			}
		}

		.img-bar {
			min-height: 50px;
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			align-items: flex-end;
			margin-left: -10px;
			margin-top: -10px;

			.image-item {
				flex-shrink: 0;
				flex-grow: 0;
				margin-top: 10px;
				margin-left: 10px;
				position: relative;

				&:hover {
					.image-operate {
						display: flex;
					}
				}

				.image-operate {
					position: absolute;
					left: 0;
					top: 0;
					right: 0;
					bottom: 10px;
					display: none;
					justify-content: center;
					align-items: center;
					background-color: rgba(0, 0, 0, 0.5);
					border-radius: 2px;

					i {
						cursor: pointer;
						color: #fff;
						font-size: 22px;
					}
				}
			}

			.el-button {
				margin-left: 10px;
				position: relative;
				top: -10px;
			}
		}

		.operate-bar {
			/*justify-content: center;*/
			padding: 20px 0;
		}

		.params {
			& > .el-input .el-input__inner {
				border-right: none;
				border-top-right-radius: 0;
				border-bottom-right-radius: 0;
			}

			& > .el-select {
				.el-input__inner {
					border-top-left-radius: 0;
					border-bottom-left-radius: 0;
				}
			}
		}
	}
</style>
